<template>
  <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0 md:space-x-4">
      <!-- 左侧：过滤条件 -->
      <div class="flex flex-col sm:flex-row sm:items-center space-y-3 sm:space-y-0 sm:space-x-4">
        <!-- 状态过滤 -->
        <div class="flex items-center space-x-2">
          <Filter class="w-4 h-4 text-gray-500" />
          <span class="text-sm font-medium text-gray-700">状态:</span>
          <div class="flex space-x-1">
            <button
              v-for="status in statusOptions"
              :key="status.value"
              @click="selectStatus(status.value)"
              class="px-3 py-1.5 text-sm font-medium rounded-lg transition-colors"
              :class="[
                selectedStatus === status.value
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              ]"
            >
              {{ status.label }}
            </button>
          </div>
        </div>
        
        <!-- 学段过滤 -->
        <div class="flex items-center space-x-2">
          <GraduationCap class="w-4 h-4 text-gray-500" />
          <span class="text-sm font-medium text-gray-700">学段:</span>
          <div class="flex space-x-1">
            <button
              v-for="grade in gradeLevelOptions"
              :key="grade.value"
              @click="selectGradeLevel(grade.value)"
              class="px-3 py-1.5 text-sm font-medium rounded-lg transition-colors"
              :class="[
                selectedGradeLevel === grade.value
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              ]"
            >
              {{ grade.label }}
            </button>
          </div>
        </div>
      </div>
      
      <!-- 右侧：排序和搜索 -->
      <div class="flex flex-col sm:flex-row sm:items-center space-y-3 sm:space-y-0 sm:space-x-4">
        <!-- 排序 -->
        <div class="flex items-center space-x-2">
          <ArrowUpDown class="w-4 h-4 text-gray-500" />
          <span class="text-sm font-medium text-gray-700">排序:</span>
          <select
            v-model="selectedSort"
            @change="handleSortChange"
            class="px-3 py-1.5 text-sm font-medium bg-gray-100 text-gray-700 rounded-lg border-0 focus:ring-2 focus:ring-blue-500 transition-all cursor-pointer"
          >
            <option v-for="sort in sortOptions" :key="sort.value" :value="sort.value">
              {{ sort.label }}
            </option>
          </select>
        </div>
        
        <!-- 搜索框 -->
        <div class="relative">
          <input
            v-model="searchQuery"
            @input="handleSearch"
            type="text"
            placeholder="搜索标题..."
            class="pl-10 pr-4 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all w-full sm:w-48"
          />
          <Search class="w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2" />
          
          <!-- 清除按钮 -->
          <button
            v-if="searchQuery"
            @click="clearSearch"
            class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
          >
            <X class="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
    
    <!-- 当前过滤条件显示 -->
    <div v-if="hasActiveFilters" class="mt-4 pt-4 border-t border-gray-200">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-2">
          <span class="text-sm text-gray-600">当前筛选:</span>
          <div class="flex flex-wrap gap-2">
            <span v-if="selectedStatus !== 'all'" class="px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
              {{ getStatusLabel(selectedStatus) }}
            </span>
            <span v-if="selectedGradeLevel !== 'all'" class="px-2 py-1 text-xs bg-purple-100 text-purple-800 rounded-full">
              {{ getGradeLevelLabel(selectedGradeLevel) }}
            </span>
            <span v-if="searchQuery" class="px-2 py-1 text-xs bg-green-100 text-green-800 rounded-full">
              搜索: "{{ searchQuery }}"
            </span>
          </div>
        </div>
        
        <button
          @click="resetFilters"
          class="text-sm text-blue-600 hover:text-blue-700 font-medium"
        >
          重置筛选
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { 
  Filter, 
  GraduationCap, 
  ArrowUpDown, 
  Search,
  X
} from 'lucide-vue-next';
import { debounce } from '@/utils/performance';

/**
 * FilterBar 组件
 * 提供过滤和排序功能
 */

// ==================== Props ====================
const props = defineProps({
  /**
   * 默认状态
   */
  defaultStatus: {
    type: String,
    default: 'all',
  },
  
  /**
   * 默认学段
   */
  defaultGradeLevel: {
    type: String,
    default: 'all',
  },
  
  /**
   * 默认排序
   */
  defaultSort: {
    type: String,
    default: 'newest',
  },
});

// ==================== Emits ====================
const emit = defineEmits(['filter-change', 'sort-change', 'search']);

// ==================== Refs ====================
const selectedStatus = ref(props.defaultStatus);
const selectedGradeLevel = ref(props.defaultGradeLevel);
const selectedSort = ref(props.defaultSort);
const searchQuery = ref('');

// ==================== Options ====================

/**
 * 状态选项
 */
const statusOptions = [
  { value: 'all', label: '全部' },
  { value: 'completed', label: '已批改' },
  { value: 'processing', label: '批改中' },
  { value: 'pending', label: '待批改' },
  { value: 'draft', label: '草稿' },
];

/**
 * 学段选项
 */
const gradeLevelOptions = [
  { value: 'all', label: '全部' },
  { value: 'primary', label: '小学' },
  { value: 'middle', label: '初中' },
  { value: 'high', label: '高中' },
];

/**
 * 排序选项
 */
const sortOptions = [
  { value: 'newest', label: '最新发布' },
  { value: 'oldest', label: '最早发布' },
  { value: 'score-high', label: '分数从高到低' },
  { value: 'score-low', label: '分数从低到高' },
];

// ==================== Computed ====================

/**
 * 是否有激活的过滤条件
 */
const hasActiveFilters = computed(() => {
  return selectedStatus.value !== 'all' || 
         selectedGradeLevel.value !== 'all' || 
         searchQuery.value !== '';
});

// ==================== Methods ====================

/**
 * 选择状态
 */
const selectStatus = (status) => {
  selectedStatus.value = status;
  emitFilterChange();
};

/**
 * 选择学段
 */
const selectGradeLevel = (gradeLevel) => {
  selectedGradeLevel.value = gradeLevel;
  emitFilterChange();
};

/**
 * 处理排序变化
 */
const handleSortChange = () => {
  emit('sort-change', selectedSort.value);
};

/**
 * 处理搜索（防抖）
 * 使用500ms防抖避免频繁触发搜索
 */
const handleSearch = debounce(() => {
  emit('search', searchQuery.value);
}, 500);

/**
 * 清除搜索
 */
const clearSearch = () => {
  searchQuery.value = '';
  emit('search', '');
};

/**
 * 重置所有过滤条件
 */
const resetFilters = () => {
  selectedStatus.value = 'all';
  selectedGradeLevel.value = 'all';
  selectedSort.value = 'newest';
  searchQuery.value = '';
  
  emitFilterChange();
  emit('sort-change', 'newest');
  emit('search', '');
};

/**
 * 触发过滤变化事件
 */
const emitFilterChange = () => {
  const filters = {};
  
  if (selectedStatus.value !== 'all') {
    filters.status = selectedStatus.value;
  }
  
  if (selectedGradeLevel.value !== 'all') {
    filters.gradeLevel = selectedGradeLevel.value;
  }
  
  emit('filter-change', filters);
};

/**
 * 获取状态标签
 */
const getStatusLabel = (value) => {
  const option = statusOptions.find(o => o.value === value);
  return option ? option.label : value;
};

/**
 * 获取学段标签
 */
const getGradeLevelLabel = (value) => {
  const option = gradeLevelOptions.find(o => o.value === value);
  return option ? option.label : value;
};
</script>

<style scoped>
/* 确保select样式一致 */
select {
  appearance: none;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
  background-position: right 0.5rem center;
  background-repeat: no-repeat;
  background-size: 1.5em 1.5em;
  padding-right: 2.5rem;
}
</style>

